{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "Faiss是一个由facebook开发以用于高效相似性搜索和密集向量聚类的库。它能够在任意大小的向量集中进行搜索。它还包含用于评估和参数调整的支持代码。Faiss是用C++编写的，带有Python的完整接口。一些最有用的算法是在GPU上实现的。Faiss官方仓库为:[faiss](https://github.com/facebookresearch/faiss)。\n",
    "\n",
    "所谓相似性搜索是指通过比较多维空间中数据之间的相似性来搜索与输入数据最相似的目标数据。例如人脸识别中，通过比较人脸向量之前的距离来识别当前人脸与哪张人脸相似。因此，该技术被广泛应用于信息检索、计算机视觉、数据分析等领域。如果要检索的数据很多时，那么就需要一个向量检索库来加速检索。Faiss包含多种相似性搜索方法，并提供cpu和gpu版本支持。Faiss的优势在于通过较小的精度损失提高向量相似度的检索速度和减少内存使用量。本文主要讲述faiss的python3接口使用。faiss官方教程见：[faiss官方教程](https://github.com/facebookresearch/faiss/wiki)。\n",
    "\n",
    "对于Faiss，linux系统的安装如下：\n",
    "\n",
    "```\n",
    "# CPU安装\n",
    "pip install faiss-cpu\n",
    "# GPU安装\n",
    "pip install faiss-gpu\n",
    "```\n",
    "\n",
    "windows系统的安装需要conda，安装指令如下。使用前需要conda activate激活环境，不要直接用pip安装。\n",
    "\n",
    "```\n",
    "# CPU安装\n",
    "conda install -c pytorch faiss-cpu\n",
    "\n",
    "# GPU安装\n",
    "conda install -c pytorch faiss-gpu\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "# 1 基础使用\r\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 1.1 入门\n",
    "\n",
    "**数据库的建立**\n",
    "\n",
    "Faiss可以处理固定维度的向量集合，这些集合可以存储在矩阵中。Faiss仅使用32位浮点矩阵，其中矩阵的列表示向量的特征，行表示向量样本数。一般来说进行向量检索，我们需要两个矩阵：\n",
    "+ 索引矩阵，索引矩阵包含所有必须索引的向量，我们将在其中搜索。其维度为[nb向量样本数,d向量维度]。\n",
    "+ 查询矩阵，查询矩阵。它的大小是[nq向量样本数,d向量维度]。如果我们只有一个查询向量，则nq=1。\n",
    "\n",
    "下面例子介绍了faiss所需输入矩阵的例子。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import numpy as np\r\n",
    "# 向量特征维度\r\n",
    "d = 64               \r\n",
    "# 索引矩阵向量样本数          \r\n",
    "nb = 10000\r\n",
    "# 查询矩阵向量样本数                   \r\n",
    "nq = 1000        \r\n",
    "# 设计随机种子   \r\n",
    "np.random.seed(42)             \r\n",
    "# 随机生成0到1的数据，简历索引矩阵，但是必须要是float32类型\r\n",
    "xb = np.random.random((nb, d)).astype('float32')\r\n",
    "# 索引矩阵第一列加上扰动\r\n",
    "xb[:, 0] += np.arange(nb) / 1000.\r\n",
    "# 建立查询矩阵\r\n",
    "xq = np.random.random((nq, d)).astype('float32')\r\n",
    "xq[:, 0] += np.arange(nq) / 1000."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "**建立索引库**\n",
    "\n",
    "Faiss是围绕索引对象构建的。它会预载索引矩阵，并可选地对其进行预处理以提高搜索效率。索引方式有多种类型，我们将使用最简单的版本，只对其执行最简单的L2距离（欧氏距离）搜索，也就是IndexFlatL2。在预载索引矩阵前，还需要设定向量的维度d，此外大多数索引方式还需要一个训练阶段，以分析向量的分布。对于IndexFlatL2，我们可以跳过此操作，所以L2距离挺慢，属于暴力检索，但是精度高。在faiss中，预载索引矩阵使用add函数，检索查询矩阵用search函数。同时通过is_trained，表示向量是否训练，如果是false就表示需要增加训练向量阶段，通过ntotal表示索引向量的数量。建立索引库的示例如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "10000\n"
     ]
    }
   ],
   "source": [
    "# 加载faiss库\r\n",
    "import faiss            \r\n",
    "# 设置检索维度       \r\n",
    "index = faiss.IndexFlatL2(d)   \r\n",
    "# 判断该索引方式是否已经训练，false表示没有训练\r\n",
    "print(index.is_trained)\r\n",
    "# 添加索引库\r\n",
    "index.add(xb)    \r\n",
    "# 打印待索引向量数     \r\n",
    "print(index.ntotal)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "**向量检索**\n",
    "\n",
    "对索引执行的基本搜索操作是k近邻搜索，即对于每个查询向量，在数据库中查找其k个相似向量。faiss中使用search进行查询，search函数返回两个unumpy结构矩阵：\n",
    "\n",
    "+ 检索距离矩阵D，维度为[nq查询向量样本数，k相似向量数]。其中列表示与k个相似向量的距离，距离从近到远排序。\n",
    "+ 检索结果距离I，维度为[nq查询向量样本数，k相似向量数]。其中列表示索引库中k个相似向量的id号，相似度从高到低排序。\n",
    "\n",
    "向量检索的代码如下所示，由于每一个第一个向量的第一个特征都添加了近似于id的值。因此，就查询结果而言，查询向量的相似索引向量id号靠近查询向量的id号。比如第一个查询向量id号为0，其索引向量的id也靠近0。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "耗时2.492363214492798s\n",
      "[[ 234  642  860  369  820]\n",
      " [ 145  430   49   27   62]\n",
      " [ 200  279  193  331  564]\n",
      " [1449  453  515 1173 1502]\n",
      " [ 108  442  133 1273  323]]\n",
      "---分割线---\n",
      "[[ 842  781 1939 1535 2579]\n",
      " [ 321 1591  265 1449  873]\n",
      " [1687 1530 1257 1370  942]\n",
      " [1403  373 1032  862 1975]\n",
      " [ 852  211  673  937  228]]\n"
     ]
    }
   ],
   "source": [
    "import time\r\n",
    "\r\n",
    "# 设置查找5个相近向量\r\n",
    "k = 5            \r\n",
    "# 索引库健全性检查，没出问题表明库加载成功             \r\n",
    "D, I = index.search(xb[:5], k)\r\n",
    "\r\n",
    "# 开始时间\r\n",
    "start = time.time()\r\n",
    "# 实际检索\r\n",
    "D, I = index.search(xq, k)    \r\n",
    "# 结束时间\r\n",
    "end = time.time()\r\n",
    "# 这里用的是一台很弱的电脑，速度慢正常。\r\n",
    "print(\"耗时{}s\".format(end-start))\r\n",
    "\r\n",
    "# 前五个查询向量的检索结果 \r\n",
    "print(I[:5])        \r\n",
    "print('---分割线---')\r\n",
    "# 最后五个查询向量的检索结果\r\n",
    "print(I[-5:])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "**上面的程序用numpy直接的计算方式如下，如果维度不高，样本不多，速度要比faiss快。但是如果数据很复杂，以下的程序不要运行，会导致系统崩溃的。**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "\r\n",
    "# 矩阵向量l2距离计算\r\n",
    "def dist(xq, xb):\r\n",
    "    xq2 = np.sum(xq**2, axis=1, keepdims=True)\r\n",
    "    xb2 = np.sum(xb**2, axis=1, keepdims=True)\r\n",
    "    xqxb = np.dot(xq,xb.T)\r\n",
    "    # faiss在计算l2距离的时候没有开方，加快速度\r\n",
    "    # return np.sqrt(xq2 - 2 * xqxb + xb2.T)\r\n",
    "    return xq2 - 2 * xqxb + xb2.T\r\n",
    "\r\n",
    "# 获取结果\r\n",
    "def get_result(dst,k = 5):\r\n",
    "    D = np.sort(dst)[:,:k]\r\n",
    "    I = np.argsort(dst)[:,:k]\r\n",
    "    return D,I \r\n",
    "\r\n",
    "# 开始时间\r\n",
    "start = time.time()\r\n",
    "# dst = dist(xq,xb)\r\n",
    "# D_, I_ = get_result(dst,k)\r\n",
    "# 结束时间\r\n",
    "end = time.time()\r\n",
    "# 这里用的是一台很弱的电脑，速度慢正常。\r\n",
    "# print(\"耗时{}s\".format(end-start))\r\n",
    "\r\n",
    "# 前五个查询向量的检索结果 \r\n",
    "# print(I[:5])        \r\n",
    "# print('---分割线---')\r\n",
    "# 最后五个查询向量的检索结果\r\n",
    "# print(I[-5:])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 1.2 加快检索速度\n",
    "\n",
    "前面的代码可以看到，检索速度太慢，尤其是在很弱性能的电脑上。为了加快检索速度，在Faiss中，将数据集分割成若干部分，然后在d维空间中定义了Voronoi单元，每个数据库向量都落在其中一个单元中。这个就是基于Voronoi图的空间最近邻近查询。在搜索时，查询向量先判断落在哪个单元上，然后将其与所在的单元中的索引向量和几个相邻单元的索引向量进行比较。\n",
    "\n",
    "在Faiss中通过设置IndexIVFFlat索引方式完成，但是这种类型的索引需要一个训练阶段，而且可以在与数据库向量具有相同分布的任何向量集合上执行。IndexIVFFlat还需要另一个索引量化器，通过该量化器将各个索引向量分配给Voronoi单元，这一操作一般通过使用IndexFlatL2来实现。这种方式建库耗时，用于检索的相邻单元数量越少，检索速度越快，精度越低。需要实际情况平衡精度和速度设置用于检索的相邻单元数量。\n",
    "\n",
    "在IndexIVFFlat搜索方法有两个参数：用于设置单元格数量的nlist，和设置在多少个相近单元进行查找nprobe（默认为一个）。 nprob的增加会导致检索速度线性增加，但是检索精度也会随之上升。一个检索示例如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "# 单元数\r\n",
    "nlist = 100\r\n",
    "# 查询向量个数\r\n",
    "k = 5\r\n",
    "# 设置量化器建立检索空间\r\n",
    "quantizer = faiss.IndexFlatL2(d)\r\n",
    "# 向量维度，单元数\r\n",
    "index = faiss.IndexIVFFlat(quantizer, d, nlist)\r\n",
    "# 检索库没有被训练\r\n",
    "print(index.is_trained)\r\n",
    "# 训练检索库\r\n",
    "index.train(xb)\r\n",
    "print(index.is_trained)\r\n",
    "\r\n",
    "# 这一操作还是耗时\r\n",
    "index.add(xb)             "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "**在1个相近单元上进行查找**\n",
    "\n",
    "可以看到检索速度变快很多，但是精度会下降。但是与前面的L2检索结果不完全相同。这是因为某些结果不在带检索的Voronoi单元中。因此，检索时访问更多的单元可能会被证明是有用的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "耗时0.09508228302001953s\n",
      "[[ 937 1026  879  461  313]\n",
      " [ 321  927  514  581  960]\n",
      " [1530 1216 1924 1518 1497]\n",
      " [1032 1998 1185 2109 1500]\n",
      " [ 211  228  412  267   35]]\n"
     ]
    }
   ],
   "source": [
    "# 默认1个相近单元用于查找\r\n",
    "print(index.nprobe)\r\n",
    "# 开始时间\r\n",
    "start = time.time()\r\n",
    "D, I = index.search(xq, k) \r\n",
    "# 结束时间\r\n",
    "end = time.time()\r\n",
    "# 这里用的是一台很弱的电脑，速度慢正常。\r\n",
    "print(\"耗时{}s\".format(end-start))\r\n",
    "# 前五个向量检索结果\r\n",
    "print(I[-5:])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "**在多个相近单元上进行查找**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "耗时0.2911374568939209s\n",
      "[[ 842  781 1939 1535 1951]\n",
      " [ 321  265 1449  873  947]\n",
      " [1687 1530 1370  942 1216]\n",
      " [1403  373 1032 1975 1411]\n",
      " [ 852  211  673  937  228]]\n"
     ]
    }
   ],
   "source": [
    "# 设置在多少个相近单元进行查找\r\n",
    "index.nprobe = 10\r\n",
    "# 开始时间\r\n",
    "start = time.time()\r\n",
    "D, I = index.search(xq, k) \r\n",
    "# 结束时间\r\n",
    "end = time.time()\r\n",
    "# 这里用的是一台很弱的电脑，速度慢正常。\r\n",
    "print(\"耗时{}s\".format(end-start))\r\n",
    "# 前五个向量检索结果\r\n",
    "print(I[-5:])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "**在所有相近单元上进行查找**\r\n",
    "\r\n",
    "当nprobe=nlist，表示在所有的数据单元上进行查找，这种方式会给出给出与直接L2检索相同的结果，但速度很慢。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "耗时0.5938379764556885s\n",
      "[[ 842  781 1939 1535 2579]\n",
      " [ 321 1591  265 1449  873]\n",
      " [1687 1530 1257 1370  942]\n",
      " [1403  373 1032  862 1975]\n",
      " [ 852  211  673  937  228]]\n"
     ]
    }
   ],
   "source": [
    "# 设置在多少个相近单元进行查找\r\n",
    "index.nprobe = nlist\r\n",
    "# 开始时间\r\n",
    "start = time.time()\r\n",
    "D, I = index.search(xq, k) \r\n",
    "# 结束时间\r\n",
    "end = time.time()\r\n",
    "# 这里用的是一台很弱的电脑，速度慢正常。\r\n",
    "print(\"耗时{}s\".format(end-start))\r\n",
    "# 前五个向量检索结果\r\n",
    "print(I[-5:])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 1.3 更低的内存占用\n",
    "\n",
    "我们看到的索引IndexFlatL2和IndexIVFFlat都存储完整向量。为了扩展到超大数据集，Faiss提供了各种变体，使用基于乘积量化器的有损压缩来压缩存储的向量。向量仍然存储在Voronoi 单元中，但它们的大小减少到可配置的字节数m（特征维度d必须是m的倍数）。\n",
    "\n",
    "压缩基于乘积量化器，可以看作是额外的量化级别，应用于要编码的向量的子向量。在这种情况下，由于向量没有精确存储，因此搜索方法返回的距离也是近似值。但是这种方法精度不高，而且训练模型时间很长，谨慎使用。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 879 1951 1099  895]\n",
      " [ 907  906  828 1453]\n",
      " [1687 1216 1530 1247]\n",
      " [1346 1398 1599 1141]\n",
      " [ 673  545  894  267]]\n"
     ]
    }
   ],
   "source": [
    "nlist = 100\n",
    "# 子量化器的数量\n",
    "m = 8   \n",
    "k = 4\n",
    "# 设置量化器建立检索空间\n",
    "quantizer = faiss.IndexFlatL2(d) \n",
    "# 8指定每个子向量编码为8位\n",
    "index = faiss.IndexIVFPQ(quantizer, d, nlist, m, 8)\n",
    "index.train(xb)\n",
    "index.add(xb)\n",
    "D, I = index.search(xb[:5], k) \n",
    "index.nprobe = 10             \n",
    "# 搜索\n",
    "D, I = index.search(xq, k)     \n",
    "print(I[-5:])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "# 2 构建指标"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 2.1 度量指标\n",
    "\n",
    "Faiss支持两种度量方法，L2（欧式距离）和内积。\n",
    "\n",
    "+ 对于L2距离，Faiss计算L2距离时没有开平方根，如果需要精确距离，则需要额外的平方根。\n",
    "+ 对于内积，这一方法是依据余弦相似度。余弦相似度是通过计算两个向量的夹角余弦值来评估它们的相似度，余弦相似度越大，表示向量的夹角越小，那么意味着两个向量越相似。余弦相似度的计算方法为两个向量的内积除以两个向量的模。但是一般情况下，只计算内积而不计算余弦相似度，当两个向量都经过归一化处理，内积计算结果就是余弦相似度。在faiss通过用IndexFlatIP建立内积索引。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "直接计算内积，代码如下，精度不高。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "10000\n",
      "耗时1.2941181659698486s\n",
      "[[9763 9880 9553 9863 9034]\n",
      " [9073 6585 9863 3904 9763]\n",
      " [9814 9766 9880 7796 9815]\n",
      " [9863 9553 9763 9003 9682]\n",
      " [9916 9763 9880 8035 9709]]\n",
      "[[32.214005 31.82538  31.135605 31.076077 31.035263]\n",
      " [20.439157 20.378412 20.31539  20.28349  20.214535]\n",
      " [27.588043 27.546564 27.50164  27.338028 27.227661]\n",
      " [27.075897 26.859488 26.714897 26.675337 26.580912]\n",
      " [27.065765 26.823675 26.782066 26.74991  26.71664 ]]\n"
     ]
    }
   ],
   "source": [
    "# 加载faiss库\n",
    "import faiss            \n",
    "# 设置检索维度       \n",
    "index = faiss.IndexFlatIP(d)   \n",
    "# 判断该索引方式是否已经训练，false表示没有训练\n",
    "print(index.is_trained)\n",
    "# 添加索引库\n",
    "index.add(xb)    \n",
    "# 打印待索引向量数     \n",
    "print(index.ntotal)\n",
    "import time\n",
    "\n",
    "\n",
    "# 设置查找5个相近向量\n",
    "k = 5            \n",
    "# 索引库健全性检查，没出问题表明库加载成功             \n",
    "D, I = index.search(xb[:5], k)\n",
    "# 开始时间\n",
    "start = time.time()\n",
    "# 实际检索\n",
    "D, I = index.search(xq, k)    \n",
    "# 结束时间\n",
    "end = time.time()\n",
    "# 这里用的是一台很弱的电脑，速度慢正常。\n",
    "print(\"耗时{}s\".format(end-start))\n",
    "\n",
    "# 前五个查询向量的检索结果，前五个的检索id应该接近0\n",
    "print(I[:5])        \n",
    "print(D[:5])        "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "数据归一化后，计算内积，代码如下。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "10000\n",
      "耗时1.6847233772277832s\n",
      "[[ 860 1240  234  618  642]\n",
      " [ 145  273  348  437  228]\n",
      " [1223  200  279  193  605]\n",
      " [1502 1449 1696  515 1415]\n",
      " [ 442  323  133 1273  108]]\n",
      "[[0.8677575  0.86685914 0.86608535 0.8649474  0.86269784]\n",
      " [0.83961076 0.82170016 0.81780475 0.81556916 0.81182253]\n",
      " [0.8426961  0.83725685 0.8371294  0.83701724 0.83649486]\n",
      " [0.8574949  0.8456532  0.8434802  0.8426977  0.83955705]\n",
      " [0.848532   0.8466242  0.84535056 0.8434353  0.84117293]]\n"
     ]
    }
   ],
   "source": [
    "# 加载faiss库\r\n",
    "import faiss            \r\n",
    "# 设置检索维度       \r\n",
    "index = faiss.IndexFlatIP(d)   \r\n",
    "# 判断该索引方式是否已经训练，false表示没有训练\r\n",
    "print(index.is_trained)\r\n",
    "\r\n",
    "xb_ = xb.copy()\r\n",
    "# 正则化\r\n",
    "faiss.normalize_L2(xb_)\r\n",
    "# 添加索引库\r\n",
    "index.add(xb_)    \r\n",
    "# 打印待索引向量数     \r\n",
    "print(index.ntotal)\r\n",
    "import time\r\n",
    "\r\n",
    "\r\n",
    "# 设置查找5个相近向量\r\n",
    "k = 5            \r\n",
    "# 开始时间\r\n",
    "start = time.time()\r\n",
    "# 实际检索\r\n",
    "xq_ = xq.copy()\r\n",
    "# 正则化\r\n",
    "faiss.normalize_L2(xq_)\r\n",
    "D, I = index.search(xq_, k)    \r\n",
    "# 结束时间\r\n",
    "end = time.time()\r\n",
    "# 这里用的是一台很弱的电脑，速度慢正常。\r\n",
    "print(\"耗时{}s\".format(end-start))\r\n",
    "\r\n",
    "# 前五个查询向量的检索结果 \r\n",
    "print(I[:5])        \r\n",
    "print(D[:5])   "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "可以numpy直接计算归一化，计算内积，推荐这种方式，代码如下。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "10000\n",
      "耗时1.384207010269165s\n",
      "[[ 860 1240  234  618  642]\n",
      " [ 145  273  348  437  228]\n",
      " [1223  200  279  193  605]\n",
      " [1502 1449 1696  515 1415]\n",
      " [ 442  323  133 1273  108]]\n",
      "[[0.8677576  0.8668592  0.86608535 0.8649473  0.8626978 ]\n",
      " [0.83961076 0.8217001  0.8178047  0.8155691  0.8118226 ]\n",
      " [0.8426961  0.83725685 0.8371294  0.83701736 0.836495  ]\n",
      " [0.8574948  0.8456532  0.8434803  0.8426978  0.839557  ]\n",
      " [0.8485321  0.8466241  0.84535056 0.8434351  0.84117293]]\n"
     ]
    }
   ],
   "source": [
    "# 加载faiss库\r\n",
    "import faiss            \r\n",
    "# 设置检索维度       \r\n",
    "index = faiss.IndexFlatIP(d)   \r\n",
    "# 判断该索引方式是否已经训练，false表示没有训练\r\n",
    "print(index.is_trained)\r\n",
    "\r\n",
    "# 归一化\r\n",
    "xb_ = xb.copy()/np.linalg.norm(xb)\r\n",
    "# 正则化\r\n",
    "faiss.normalize_L2(xb_)\r\n",
    "# 添加索引库\r\n",
    "index.add(xb_)    \r\n",
    "# 打印待索引向量数     \r\n",
    "print(index.ntotal)\r\n",
    "import time\r\n",
    "\r\n",
    "# 设置查找5个相近向量\r\n",
    "k = 5            \r\n",
    "# 开始时间\r\n",
    "start = time.time()\r\n",
    "# 实际检索\r\n",
    "# 归一化\r\n",
    "xq_ = xq.copy()/np.linalg.norm(xq)\r\n",
    "# 正则化\r\n",
    "faiss.normalize_L2(xq_)\r\n",
    "D, I = index.search(xq_, k)    \r\n",
    "# 结束时间\r\n",
    "end = time.time()\r\n",
    "# 这里用的是一台很弱的电脑，速度慢正常。\r\n",
    "print(\"耗时{}s\".format(end-start))\r\n",
    "\r\n",
    "# 前五个查询向量的检索结果 \r\n",
    "print(I[:5])        \r\n",
    "print(D[:5]) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "此外还有一种常用的距离：马氏距离Mahalanobis，faiss中马氏距离的用法见[mahalnobis_to_L2.ipynb](https://gist.github.com/mdouze/6cc12fa967e5d9911580ef633e559476)。关于马氏距离的说明见[马氏距离(Mahalanobis Distance)](https://zhuanlan.zhihu.com/p/46626607)。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 2.2 Faiss 构建模块\n",
    "\n",
    "Faiss 建立在一些具有非常高效实现的基本算法之上：k-means 聚类、PCA、PQ 编码/解码。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "**聚类**\n",
    "\n",
    "Faiss提供了一种高效的k-means实现。如下所示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from sklearn.datasets import make_blobs\r\n",
    "import matplotlib.pyplot as plt\r\n",
    "# 随机创建数据\r\n",
    "# n_features特征维度，n_samples样本数，centers聚类中心也可以理解为label数，cluster每个类别数据的方差，random_state随机种子\r\n",
    "data, label = make_blobs(n_features=3, n_samples=1000, centers= 5, cluster_std= 0.5 , random_state = 42)\r\n",
    "data = data.astype('float32')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1000, 3)\n",
      "(1000,)\n"
     ]
    }
   ],
   "source": [
    "# 查看数据\r\n",
    "print(data.shape)\r\n",
    "# 查看标签\r\n",
    "print(label.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clustering 1000 points in 3D to 5 clusters, redo 1 times, 1 iterations\n",
      "  Preprocessing in 0.00 s\n",
      "  Iteration 0 (0.69 s, search 0.39 s): objective=53190.2 imbalance=1.456 nsplit=0       \r"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0.6"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 簇中心\r\n",
    "ncentroids = 5\r\n",
    "# 迭代次数\r\n",
    "niter = 1\r\n",
    "verbose = True\r\n",
    "d = data.shape[1]\r\n",
    "# 创建模型\r\n",
    "kmeans = faiss.Kmeans(d, ncentroids, niter=niter, verbose=verbose)\r\n",
    "# 训练模型\r\n",
    "kmeans.train(data)\r\n",
    "D, I = kmeans.index.search(data, 1)\r\n",
    "# 精度\r\n",
    "sum(label==I.reshape(-1))/len(label)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.6"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# sklearn聚类\r\n",
    "from sklearn.cluster import KMeans\r\n",
    "import matplotlib.pyplot as plt\r\n",
    "# KMeans聚类\r\n",
    "model = KMeans(n_clusters=5)\r\n",
    "pred = model.fit_predict(data)\r\n",
    "# 精度\r\n",
    "sum(label==pred)/len(label)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "一般来说当样本维度过高，或数据量大的时候，faiss进行聚类是个很不错的选择。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "**降维**\n",
    "\n",
    "faiss降维主要使用PCA，速度比sklearn快得多。示例代码如下"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 随机创建数据\r\n",
    "# n_features特征维度，n_samples样本数，centers聚类中心也可以理解为label数，cluster每个类别数据的方差，random_state随机种子\r\n",
    "data, label = make_blobs(n_features = 512, n_samples=1000, centers= 10, cluster_std= 0.5 , random_state = 42)\r\n",
    "data = data.astype('float32')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.collections.PathCollection at 0x7fb21413a790>"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXwAAAD8CAYAAAB0IB+mAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMi4zLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvIxREBQAAHfFJREFUeJzt3XucVXW9//HXZ2bPMMNwh4FAbqOChnjDkTCFk4BK6BEr6/ArFdTiVFaWpWLmSTtmWv4q7EIPClPzkuYN6ufRFC/VUdCBRLloEogMchmS+wBz+/z+2AscYYaZvffal9nr/Xw8eLD32uu719slvNnzXWuvZe6OiIjkv4JsBxARkcxQ4YuIRIQKX0QkIlT4IiIRocIXEYkIFb6ISESo8EVEIkKFLyISESp8EZGIiGU7QHN9+vTxoUOHZjuGiEiHsnjx4i3uXt7WejlV+EOHDqWqqirbMUREOhQzW9ue9TSlIyISESp8EZGIUOGLiERETs3hS/5qbGxiUdVqnnl+Bevf3crqtZupq3v/0txmMHpUBd+deT5lZZ2ymFQkf7W78M3sTuA8YLO7jwyW9QIeBIYCbwOfcfetZmbALGAyUAtMd/cl4UaXjmJzzQ6uvPYB3tu6m737Glpcxx0WLV7D5E/P4rhj+3PHDz9LLFaY4aQi+S2RKZ27gEkHLZsJLHD3YcCC4DnAx4Fhwa8ZwOzUYkpHVV/fyFeuvp8Nm7a3WvYHW/7GBj73+Tk0NDalOZ1ItLS78N39L8B7By2eAtwdPL4buKDZ8ns8biHQw8z6pxpWOp6/vvgPtm2vJdEbq23cvJP5T/w9PaFEIirVg7b93H1D8Hgj0C94fASwrtl61cEyiZgnnn6dfe38ZH+w3977vyGnEYm20M7S8fjNcRO+Q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LMVq7qfEP4g0Bc97A9ua/cOfK/u1AqgBfhtMP/3GzMrIsX3q7uuJ3wL2HeJFvx1YTIb3aapXy8yadN+YJSxt5Pw28emSrDtcTnefF6xzPfGrn96XyWz5xsy6AI8AX3f3HfEPz3Hu7maW1VPnzOw8YLO7Lzazj2UzSzvEgFHAV919kZnNIj6Fc0CO7NOexH/qqAC2AX8gfr/vjOqwhe8d5MYsreU0s+OJ/89fGvyFHwgsMbPRuZRzPzObDpwHTAj2K+TmjW5yMdMBZlZEvOzvc/dHg8WbzKy/u28Ipu42t/4OGXE6cL6ZTQZKgG7ALOJTi7HgE2mu7NdqoNrdFwXPHyZe+Lm2TycCa9y9BsDMHiW+nzO6T/N1Sifnb8zi7q+7e193H+ruQ4n/wR3l7huDnJcEZ+uMAbY3+/E048xsEvEf789399pmL+XM/mzmFWBYcPZDMTCVeM6sC+bB5wIr3f3HzV6aD0wLHk8D5mU6W3Pufp27Dwz+XE4FnnX3zwHPARcGq2U9J0Dw92WdmR0TLJpA/D4cObVPiU/ljDGzzsGfg/05M7tPs3nkOl2/iBf8vcAyYAkwvtlr1xM/i+NN4OPZztos19u8f5aOAb8Icr4OVGY52yri8+KvBr9+lcv7k/hZTv8Icl2f7TzNcp1B/OD8a8325WTi8+MLgLeIn13WK9tZm2X+GO+fpXMk8X/QVxGfkuiU7XxBrpOAqmC/Pg70zMV9CtwEvBH00u+In92W0X2qb9qKiEREvk7piIjIQVT4IiIRocIXEYkIFb6ISESo8EVEIkKFLyISESp8EZGIUOGLiETE/wf1EhRdgQyEawAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# 降到2维\r\n",
    "mat = faiss.PCAMatrix (512, 2)\r\n",
    "mat.train(data)\r\n",
    "assert mat.is_trained\r\n",
    "tr = mat.apply(data)\r\n",
    "\r\n",
    "# 数据可视化\r\n",
    "plt.scatter(tr[:, 0], tr[:, 1], s=80,c=label)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.collections.PathCollection at 0x7fb21410a610>"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXwAAAD8CAYAAAB0IB+mAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMi4zLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvIxREBQAAHexJREFUeJzt3XmUVPWd9/H3t/emWRqkIS0gtAFUxA1bggtMBEWCjjgx8eExjqiJJMYkJpooRueJJjrqxInBLOYQNeq4RENUMMcxKi5ZFLRRkc2FgArI0hr2Bnr7Pn/UBdumm+6qurV03c/rnD5ddev+6n68woeqX92619wdERHJfXmZDiAiIumhwhcRiQgVvohIRKjwRUQiQoUvIhIRKnwRkYhQ4YuIRIQKX0QkIlT4IiIRUZDpAC317dvXhwwZkukYIiJdysKFCz9y94qO1suqwh8yZAg1NTWZjiEi0qWY2fudWU9TOiIiEaHCFxGJCBW+iEhEZNUcvuSupqZmFtSs5NkXlrF23SZWvreR+vpPTs1tBqNHVfGjGWdSVlacwaQiuavThW9mdwNnABvdfWSwrA/wMDAEeA84x903mZkBM4HJQB1wgbu/Fm506So2bNzKd2c8xD837WDX7sY213GHBQtXMfnLMzn8sEpuv+VcCgry05xUJLfFM6VzDzCp1bIZwDx3HwbMC+4DfAEYFvxMB+5ILqZ0VQ0NTXz7ygdZt2FLu2Xf2tLl6/jK12bR2NSc4nQi0dLpwnf3vwD/bLV4CnBvcPte4KwWy+/zmPlAuZlVJhtWup6/vvQOm7fUEe+F1dZv3MbcJ19PTSiRiEr2Q9v+7r4uuL0e6B/cHgCsbrHemmCZRMyTzyxmdydf2b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WGWdDCzKcBad1/U6qGsytnKRcTefUB25szGTPswsyHAMcACoL+7rwseWg/0z1Csln5O7IVIc3D/AGBzi3/4s2W/VgG1wO+C6ac7zayMLNun7r6W2CVgPyBW9FuAhaR5nyZ7tsyMSfWFWcLSQc4fEpsuybj95XT3OcE61xA7++kD6cyWa8ysO/BH4LvuvjX24jnG3d3MMnronJmdAWx094Vm9vlMZumEAmAU8G13X2BmM4lN4eyVJfu0N7F3HVXAZuAPxK73nVZdtvC9i1yYpb2cZnYEsf/5i4K/8AOB18xsdDbl3MPMLgDOACYE+xWy80I32ZhpLzMrJFb2D7j7o8HiDWZW6e7rgqm7je0/Q1qcCJxpZpOBEqAnMJPY1GJB8Io0W/brGmCNuy8I7s8mVvjZtk9PAVa5ey2AmT1KbD+ndZ/m6pRO1l+Yxd0Xu3s/dx/i7kOI/cEd5e7rg5znB0frjAG2tHh7mnZmNonY2/sz3b2uxUNZsz9beBUYFhz9UARMJZYz44J58LuA5e7+sxYPzQWmBbenAXPSna0ld7/a3QcGfy6nAs+5+1eA54EvBatlPCdA8PdltZkdEiyaQOw6HFm1T4lN5Ywxs27Bn4M9OdO7TzP5yXWqfogV/P3AEuA1YHyLx64hdhTH28AXMp21Ra73+OQoHQN+FeRcDFRnONsKYvPibwQ/v8nm/UnsKKd3glzXZDpPi1wnEftw/s0W+3IysfnxecC7xI4u65PprC0yf55PjtI5mNg/6CuITUkUZzpfkOtooCbYr48DvbNxnwLXA28FvfQ/xI5uS+s+1TdtRUQiIlendEREpBUVvohIRKjwRUQiQoUvIhIRKnwRkYhQ4YuIRIQKX0QkIlT4IiIR8f8BD98RZOabBC8AAAAASUVORK5CYII=\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#调用sklearnPCA\r\n",
    "from sklearn.decomposition import PCA\r\n",
    "\r\n",
    "pca = PCA(n_components=2)\r\n",
    "tr = pca.fit_transform(data)\r\n",
    "# 数据可视化\r\n",
    "plt.scatter(tr[:, 0], tr[:, 1], s=80,c=label)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "**乘积量化**\n",
    "\n",
    "有时原始向量维度或向量数太多太高，计算相似度太慢。通过乘积量化对原始向量进行压缩，降低向量维度，压缩数据信息加快检索速度同时节省了内存空间。关于乘积量化见[ANN之乘积量化PQ](https://blog.csdn.net/tiangcs/article/details/124012169)。此外压缩后的数据可以进行恢复为原数据，一般重建误差不高，但建立量化器速度很慢。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# 数据维度\r\n",
    "d = 16\r\n",
    "# 编码维度\r\n",
    "cs = 4 \r\n",
    "\r\n",
    "# 训练数据\r\n",
    "nt = 10000\r\n",
    "xt = np.random.rand(nt, d).astype('float32')\r\n",
    "# 编码数据\r\n",
    "n = 5000\r\n",
    "x = np.random.rand(n, d).astype('float32')\r\n",
    "# 训练量化器\r\n",
    "pq = faiss.ProductQuantizer(d, cs, 8)\r\n",
    "pq.train(xt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.016456977"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 编码\r\n",
    "codes = pq.compute_codes(x)\r\n",
    "codes.shape\r\n",
    "# 解码\r\n",
    "x2 = pq.decode(codes)\r\n",
    "\r\n",
    "# 计算重建误差\r\n",
    "avg_relative_error = ((x - x2)**2).sum() / (x ** 2).sum()\r\n",
    "avg_relative_error"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "**关于faiss中其他接口的介绍和使用见[Faiss流程与原理分析](https://www.cnblogs.com/yhzhou/p/10568728.html)。**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "# 3 参考\n",
    "\n",
    "+ [faiss](https://github.com/facebookresearch/faiss)\n",
    "+ [faiss官方教程](https://github.com/facebookresearch/faiss/wiki)\n",
    "+ [马氏距离(Mahalanobis Distance)](https://zhuanlan.zhihu.com/p/46626607)\n",
    "+ [mahalnobis_to_L2.ipynb](https://gist.github.com/mdouze/6cc12fa967e5d9911580ef633e559476)\n",
    "+ [ANN之乘积量化PQ](https://blog.csdn.net/tiangcs/article/details/124012169)\n",
    "+ [Faiss流程与原理分析](https://www.cnblogs.com/yhzhou/p/10568728.html)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "py35-paddle1.2.0"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
